/**
* Copyright (c) 2016-2100 yunclouds
*/
package com.yunqian.redot.service;

import com.yunqian.exception.ServiceException;
import com.yunqian.redot.constant.BusinessType;
import com.yunqian.redot.constant.Operation;
import com.yunqian.redot.constant.OperationMenus;
import com.yunqian.redot.domain.Contents;
import com.yunqian.redot.domain.Courses;
import com.yunqian.redot.domain.dto.CourseDto;
import com.yunqian.redot.repository.ContentsRepository;
import com.yunqian.redot.repository.CoursesRepository;
import com.yunqian.service.BaseService;
import com.yunqian.util.bean.BeanUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 课程管理
 *
 * @author zsy
 * 2018-09-29 15:54:02
 */
@Service
@Log4j2
public class CoursesService extends BaseService<Courses, Long> {

    @Autowired
    private CoursesRepository coursesRepository;
    @Autowired
    private ContentsRepository contentsRepository;
    @Autowired
    private OperationLogService operationLogService;

    public void save(CourseDto dto, Long userId) {
        Courses course = dto.getCourses();
        boolean exist = coursesRepository.existsByTitle(course.getTitle());
        if(exist){
            throw new ServiceException("该报名已存在");
        }
        super.save(course);
        List<Contents> contents = dto.getContentsList();
        contents.forEach(item -> {
            item.setRelateBusiness(BusinessType.COURSES.getCode());
            item.setRelateId(course.getId());
            item.setSaveTime(new Date());
        });
        contentsRepository.saveAll(contents);
        operationLogService.save(OperationMenus.SIGN_LIST, Operation.ADD, userId);

    }

    public void update(CourseDto dto, Long userId) {
        Courses course = dto.getCourses();
        Courses origCourse = this.getById(course.getId());
        BeanUtil.copyNotNullProperties(origCourse, course);
        super.update(origCourse);
        // 删除原先的数据
        contentsRepository.deleteByRelateBusinessAndRelateId(BusinessType.COURSES.getCode(), course.getId());
        // 新增
        List<Contents> contents = dto.getContentsList();
        contents.forEach(item -> {
            item.setRelateBusiness(BusinessType.COURSES.getCode());
            item.setRelateId(course.getId());
            item.setSaveTime(new Date());
        });
        contentsRepository.saveAll(contents);
        operationLogService.save(OperationMenus.SIGN_LIST, Operation.UPDATE, userId);
    }

    public void updateStatusByTime(){
        coursesRepository.updateStatusByTime();
    }

}
